/**
Defines functions to extract the IP Address from a hostname.
*/
#include "globals.h"

/**
Function to check if we can connect to a IP Address.

@param ip_addr supplies the Ip Address.

@return the valid Ip Adrress or NULL to indicated invalid IP Address.
*/
char* 
valid_ip_addr(
    char* ip_addr
    )
{
    struct in_addr ipv4addr;
    struct hostent* hptr;

    Inet_pton(AF_INET, ip_addr, &ipv4addr);
    hptr = gethostbyaddr(&ipv4addr, sizeof(ipv4addr), AF_INET);

    if (hptr == NULL)
    {
        return NULL;
    }

    return ip_addr;
}

/**
Function to get the IP Address for a host name.

@param hostname supplies the host name.

@return the valid IP Address of the host or NULL if the host name is invalid.
*/
char* 
get_ip_addr(
    char* hostname
    )
{
    char* ip_addr;
    struct hostent* hptr;

    ip_addr = NULL;

    hptr = gethostbyname(hostname);

    if (hptr == NULL)
    {
        log_msg_str("Could not resolve hostname", hostname);
        return valid_ip_addr(hostname);
    }

    log_msg(hptr->h_name);

    switch(hptr->h_addrtype)
    {
        case AF_INET:
            ip_addr = (char*)Malloc(INET_ADDRSTRLEN*sizeof(char));
            if ((Inet_ntop(hptr->h_addrtype, *hptr->h_addr_list, ip_addr,
            INET_ADDRSTRLEN*sizeof(char))) == NULL)
            {
                free(ip_addr);
                ip_addr = NULL;
                return NULL;
            }
            break;
        default:
            err_ret("Unknown address type.");
            break;
    }
 
    return ip_addr;
}


